<template>
  <el-dialog v-model="visible" title="用户添加" :close-on-click-modal=false :destroy-on-close=true>
    <el-form :model="UserForm" label-width="80px" ref="UserAddRef" :rules="rules">
    <el-form-item label="用户名" prop="name">
      <el-input v-model="UserForm.name"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" show-password v-model="UserForm.password" />
    </el-form-item>
    <el-form-item label="确认密码" prop="passwordConfirmed">
      <el-input type="password" show-password v-model="UserForm.passwordConfirmed" />
    </el-form-item>
    <el-form-item label="姓名" prop="alias">
      <el-input v-model="UserForm.alias" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="UserForm.email" />
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="UserForm.phone" />
    </el-form-item>

    <el-form-item label="角色" prop="roles">
      <el-select
        v-model="UserForm.roles"
        multiple
        placeholder="请选择角色">
        <el-option v-for="option in roleOption" :label="option.label" :value="option.value" />
      </el-select>
    </el-form-item>

    </el-form>
    <el-button type="primary" @click="save">保存</el-button>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import apiUser from '@/api/system/user'
import {ElNotification} from 'element-plus'

const visible = ref(false)
const props = defineProps({modelValue: Boolean})
const emit = defineEmits(['update:modelValue', 'success'])

const UserAddRef = ref()
const UserForm = ref({
  name: '',
  password: '',
  passwordConfirmed: '',
  alias: '',
  email: '',
  phone: '',
  department: '',
  roles: [],
  extra: {}
})

const roleOption = ref([
  {'label': '管理员', 'value': '1'},
  {'label': '采集员', 'value': '2'}
  ])

watch(() => props.modelValue, (val) => {
  visible.value = val
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

const deleteKV = (key: string) => {
  delete UserForm.value.extra[key]
}

const save = async () => {
    try {
      const valid = await UserAddRef.value.validate()
      if (!valid) return

      const resp = apiUser.addUser(UserForm.value)
      visible.value = false
      UserAddRef.value.resetFields()

      ElNotification({message: "新增成功", type: 'success'})
      emit('success')
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

const confirmPassword = (rule: any, value: any, callback: any) => {
  if (value !== UserForm.value.password) {
    callback(new Error("两次密码不相同"))
  } else {
    callback()
  }
}

const rules = {
  name: [{"required": true, "message": "请输入姓名", "trigger": "blur"}],
  password: [{"required": true, "message": "请输入密码", "trigger": "blur"}],
  passwordConfirmed: [
    {"required": true, "message": "请确认密码", "trigger": "blur"},
    { validator: confirmPassword, trigger: 'blur' }
  ]
}
</script>

<style>
</style>
